有哪些不同的可见性说明符?

现在您已经了解了函数的基础知识,让我们进一步深入探讨 move 中函数的不同方面。

功能可见性

可见性意味着如何从定义函数的模块中访问函数。例如,任何其他模块是否可以访问该函数。因此,在某些情况下,开发人员可能需要其特定模块之外的功能,而在某些情况下则不需要。因此,为了处理这个问题,我们有两个最流行的可见性说明符:Private 和 Public。

私有函数

默认情况下,函数可见性设置为私有,这意味着该函数只能由同一模块访问,但不能在模块外部访问。让我们看下面的例子。

module examples::math { use sui::object::UID; use sui::tx_context::{Self, TxContext}; // std::string import use std::string::{Self, String}; // Declaring the Name public struct Numbers has key { id: UID, a: u8, b: u8, } // Initializing the constructor fun init(a: u8, b: u8, ctx: &mut TxContext) { let numbers = Numbers { id: object::new(ctx), name: string::utf8(name_bytes) } } fun add(n: Numbers) { let sum = n.a + n.b; } }

这里,默认情况下, add 是私有函数。

公有函数

您可以将 public 关键字与 move 函数一起使用以将其公开。公共函数可以在模块外部访问,这意味着其他模块(也称为它们的函数)也可以访问公共函数。让我们在最后一个示例中添加一个公共函数。

module examples::math { use sui::object::UID; use sui::tx_context::{Self, TxContext}; // std::string import use std::string::{Self, String}; // Declaring the Name public struct Numbers has key { id: UID, a: u8, b: u8, } // Initializing the constructor fun new(num_1: u8, num_2: u8, ctx: &mut TxContext) { let numbers = Numbers { id: object::new(ctx), a: num_1, b: num_2, } } fun add(n: Numbers) { let sum = n.a + n.b; } public fun sub(n: Numbers){ let result = n.a - n.b; } }

现在,通过将 public 关键字放在 fun 关键字之前,我们使 sub 函数成为可以在模块外部访问的公共函数。

输入函数

在move中,基本操作之一是代表各个用户的地址之间的gas对象传输。当您进行交易时, entry 函数是直接调用的。要初始化 entry 函数,我们需要确保以下三件事。

  1. 该函数应由 entry 关键字标记。
  2. 它不应该有返回值。
  3. 入口函数的最后一个参数必须是对该类型实例的 TxContext 可变引用。

让我们以我们在课程开始时讨论的“Hello World”程序为例。

#![allow(unused)] fn main() { public entry fun mint(ctx: &mut TxContext) { let object = HelloWorldObject { id: object::new(ctx), text: string::utf8(b"Hello World!") }; transfer::public_transfer(object, tx_context::sender(ctx)); } }

现在,该函数将在交易时执行,并且 &mut TxContext 是一个可变引用,有助于识别想要铸造合约的发送者的地址。函数末尾的 transfer 模块不会返回任何值,但有助于将对象存储在 Sui 全局存储中,您可以在部署模块后全局访问该对象。别担心,我们将在课程结束时详细讨论“Hello World”程序。

小结

功能可见性和入口功能在move中起着至关重要的作用。通过了解它们,您已经很厉害了。现在,我们需要更深入地研究 move 对象。让我们深入探讨一下。

quiz

提供一个编码示例,演示 move 模块中公共函数的使用。